package com.cabrida.livestar.mainstar;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cabrida.livestar.BaseActivity;
import com.cabrida.livestar.R;
import com.cabrida.livestar.config.Global;
import com.cabrida.livestar.config.HttpHelp;
import com.cabrida.livestar.config.Urls;
import com.cabrida.livestar.util.Bimp;
import com.cabrida.livestar.util.FileBitmapUtils;
import com.cabrida.livestar.util.FileUtil;
import com.cabrida.livestar.util.HttpUtils;
import com.cabrida.livestar.util.ImageUtils;
import com.cabrida.livestar.util.JsonUtils;
import com.cabrida.livestar.util.L;
import com.cabrida.livestar.util.NetworkUtils;
import com.cabrida.livestar.util.FileUtils.PathStatus;
import com.cabrida.livestar.view.GridViewExtend;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * 发布动态
 */
public class StarSendTrendActivity extends BaseActivity {
	public static final String TAG = StarSendTrendActivity.class
			.getSimpleName();
	private ImageView iv_back;
	private TextView tv_title;
	private TextView tv_right;
	private EditText et_content;
	private GridViewExtend gridView;
	private StarSendTrendGvAdapter adapter;
	private ArrayList<String> mImgList_path = new ArrayList<String>();
	private ArrayList<String> mImgList_file = new ArrayList<String>();
	private String description="";
	/**
     * 循环上传图片坐标
     */
    int posLoadImage = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_star_sendtrend);
		iv_back = (ImageView) findViewById(R.id.iv_back);
		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_right = (TextView) findViewById(R.id.tv_right);
		et_content = (EditText) findViewById(R.id.et_content);
		gridView = (GridViewExtend) findViewById(R.id.gridView);
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		iv_back.setOnClickListener(this);
		tv_right.setOnClickListener(this);
		tv_title.setText("写动态");
		tv_right.setText("发布");
		Bimp.bmp.clear();
		Bimp.drr.clear();
		Bimp.max = 0;
		mImgList_path.clear();
		mImgList_file.clear();
		adapter = new StarSendTrendGvAdapter(context);
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (arg2 == Bimp.bmp.size()) {
					img_head_perfection_click();
				}else {
					
				}
			}
		});
	}
	
	private Dialog dialogHead;
	/**
	 * 头像点击事件
	 */
	private void img_head_perfection_click() {
		showHeadDialog((Activity) context);
	}

	private void showHeadDialog(Activity activity) {
		initHeadDialogView();
		if (null != dialogHead && dialogHead.isShowing()) {
			return;
		}
		if (null != dialogHead) {
			/**
			 * 等数据加载完毕，显示对话框
			 */
			Window window = dialogHead.getWindow();
			// 设置显示动画
			window.setWindowAnimations(R.style.main_menu_animstyle);
			WindowManager.LayoutParams wl = window.getAttributes();
			wl.x = 0;
			wl.y = ((Activity) context).getWindowManager().getDefaultDisplay()
					.getHeight();
			// 以下这两句是为了保证按钮可以水平满屏
			wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
			wl.height = ViewGroup.LayoutParams.MATCH_PARENT;
			// 设置显示位置
			dialogHead.onWindowAttributesChanged(wl);
			// 设置点击外围解散
			dialogHead.setCanceledOnTouchOutside(true);
			dialogHead.show();
		}
	}

	private void initHeadDialogView() {
		LayoutInflater mInflater = LayoutInflater.from(context);
		View view = mInflater.inflate(R.layout.dialog_img_choice, null);
		LinearLayout tvFriends = (LinearLayout) view
				.findViewById(R.id.ll_album);
		tvFriends.setOnClickListener(this);
		LinearLayout tvFriendsCircle = (LinearLayout) view
				.findViewById(R.id.ll_camera);
		tvFriendsCircle.setOnClickListener(this);
		Button btnCancle = (Button) view.findViewById(R.id.btn_cancel);
		btnCancle.setOnClickListener(this);
		dialogHead = new Dialog(context, R.style.dialogWindowStyle);
		dialogHead.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialogHead.setContentView(view, new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
	}
	
	private String path = "";
	private static final int TAKE_PICTURE = 0x000000;
	private String protraitPath;
	private Bitmap protraitBitmap;
	private File protraitFile;
	private final static String FILE_SAVEPATH = Environment
			.getExternalStorageDirectory().getAbsolutePath()
			+ "/LiveStar/Portrait/";
	private Uri origUri;
	private Uri cropUri;
	private final static int CROP = 600;
	private String str_path="";
	private String str_file="";
	Uri photoUri;
    String cropFileName;
    private void photo() {
        path = "";
        if (FileUtil.createPath(FILE_SAVEPATH).equals(PathStatus.ERROR)) {
            return;
        }
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        // 照片命名
        cropFileName = "osc_camera_" + timeStamp + ".jpg";
        // 裁剪头像的绝对路径
        protraitPath = FILE_SAVEPATH + cropFileName;
        protraitFile = new File(protraitPath);
        path = protraitFile.getPath();
        Uri imageUri = Uri.fromFile(protraitFile);
        ContentValues values = new ContentValues();
        values.put(Media.TITLE, cropFileName);
        photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }
    
    @Override
    public void onActivityResult(final int requestCode, final int resultCode, final Intent imageReturnIntent) {
        Uri uri = null;
        if (resultCode != Activity.RESULT_OK)
            return;
        switch (requestCode) {
            case TAKE_PICTURE:
                if (Bimp.drr.size() < adapter.tatalImageNum && resultCode == -1) {
                    Bimp.drr.add(path);
                    if (imageReturnIntent == null) {
                        //Toast.makeText(mContext, "该版本与您手机存在不兼容问题，请'选择'图片", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Bundle bundle = imageReturnIntent.getExtras();
                    // 获取相机返回的数据，并转换为图片格式
                    Bitmap bitmap = (Bitmap) bundle.get("data");
                    FileOutputStream fout = null;
                    File file = new File(FILE_SAVEPATH);
                    file.mkdirs();
                    try {
                        fout = new FileOutputStream(cropFileName);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                        bitmap.recycle();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            fout.flush();
                            fout.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;
        }
    }
    
    /**
	 * 上传新照片
	 */
	private void uploadNewPhoto(final int pos) {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		String theThumbnail="";
		boolean isCon = true;
		try {
			String largeFileName = FileUtil.getFileName(Bimp.drr.get(pos));
			String largeFilePath = FileBitmapUtils.SDPATH + largeFileName;
			if (largeFileName.startsWith("thumb_")
                    && new File(largeFilePath).exists()) {
                theThumbnail = largeFilePath;
            } else {
            	String thumbFileName = "thumb_" + largeFileName;
                theThumbnail = FileBitmapUtils.SDPATH + thumbFileName;
                if (!new File(theThumbnail).exists()) 
                {
                	isCon = ImageUtils.createImageThumbnail(context, Bimp.drr.get(pos), theThumbnail, 800, 80);
                }
            }
			
			
			
			File file = new File(theThumbnail);
			if (isCon) {
				params.put("img", file);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_IMGUPLOAD_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "uploadNewPhoto"+"pos="+pos, response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response, "data", new JSONObject());
							String str_path = JsonUtils.getString(data,"path", "");
							String str_file = JsonUtils.getString(data,"file", "");
							mImgList_path.add(str_path);
							mImgList_file.add(str_file);
							posLoadImage++;
							if (posLoadImage == Bimp.drr.size()) {
								sendTrendBtn();
							}else if (posLoadImage < Bimp.drr.size()) {
								uploadNewPhoto(posLoadImage);
		                    }
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}
	
	/**
	 *发布动态
	 */
	private void sendTrendBtn() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		if (TextUtils.isEmpty(description)) {
			description="";
		}
		params.put("description", description);
		
		params.put("path", new JSONArray(mImgList_path));
		params.put("file", new JSONArray(mImgList_file));
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_CIRCLE_DYNAMIC_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "sendTrendBtn", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						//
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response, "data", new JSONObject());
							String message = JsonUtils.getString(data, "message", "");
							showToast(message);
							Intent intent = new Intent();
							intent.setAction(MainStarActivity.ACTION_CIRCLE_LIST);
							context.sendBroadcast(intent);
							finish();
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}
    
    @Override
    protected void onRestart() {
    	// TODO Auto-generated method stub
    	super.onRestart();
    	adapter.loading();
    }
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.iv_back:
			this.finish();
			break;
		case R.id.tv_right:
			description = et_content.getText().toString();
			if (TextUtils.isEmpty(description)&&Bimp.drr.size() == 0) {
				showToast("请输入文字或者选择图片!");
				break;
			}
			if (Bimp.drr.size() > 0 && Bimp.drr.size() <= StarSendTrendGvAdapter.tatalImageNum) {
				mImgList_path.clear();
				mImgList_file.clear();
				uploadNewPhoto(posLoadImage);
			}else {
				sendTrendBtn();
			}
			break;
			
		case R.id.ll_album:
            if (null != dialogHead) {
            	dialogHead.dismiss();
                Intent intent = new Intent(this, PicActivity.class);
                startActivity(intent);
            }
            break;
        case R.id.ll_camera:
            if (null != dialogHead) {
            	dialogHead.dismiss();
                photo();
            }
            break;
        case R.id.btn_cancel:
            if (null != dialogHead) {
            	dialogHead.dismiss();
            }
            break;

		default:
			break;
		}
	}

}
